use std::time::Instant;


use egui::{FontDefinitions, Context, pos2};
use super::platform::{Platform, PlatformDescriptor};
use winit::event::Event;

use crate::{config::AliceConfig, math::{Vector2u, Vector2f}};


#[derive(Debug,Default)]
pub struct UiOutput {
   pub texture_delta:egui::TexturesDelta,
   pub primitive: Vec<egui::ClippedPrimitive>
}

pub struct AliceUI {
    platform:Platform,
    size:Vector2u,
}

impl AliceUI {
    pub fn new(config:&AliceConfig) -> Self {
        let size = config.get_screen_size();
        Self {
            
            platform:Platform::new(PlatformDescriptor {
                physical_width:     size.x,
                physical_height:    size.y,
                scale_factor:       1.0,
                font_definitions:   FontDefinitions::default(),
                style:              Default::default(),
            }),
            size
        }
    }

    pub fn begin_frame(&mut self ,  dt:Instant) {
        self.platform.update_time(dt.elapsed().as_secs_f64());

        // let ratio = self.size.x as f32 / 1920.0;
        // self.platform.raw_input_mut().pixels_per_point = Some(ratio * 2.0);
      
        // self.platform.raw_input_mut().screen_rect = Some(egui::Rect::from_min_size(
        //     Default::default(),
        //     egui::vec2(self.size.x as f32 * 2.0, self.size.y as f32 * 2.0)
        //         / (ratio * 2.0),
        // ));
        self.platform.begin_frame();
        
    }

    pub fn update_screen_info(&mut self , pos:Vector2f, size:Vector2u) {
        self.platform.set_offset(pos);
        self.size = size
    }
 

    pub fn end_frame(&mut self ) ->  UiOutput {

        // Draw the demo application.
  
        let full_output = self.platform.end_frame(None);
        let paint_jobs = self.platform.context().tessellate(full_output.shapes);


        UiOutput {
            texture_delta:full_output.textures_delta ,
            primitive:paint_jobs

        }
    }


    pub fn ctx(&self) -> Context {
        self.platform.context()
    }

    pub fn handle_ui_event<T>(&mut self , winit_event:&Event<T>){
        self.platform.handle_event(winit_event)
       
    }



}
